// 初始化iScroll控件
var myScroll;
var mutual;
var titScroll;
var touchtime;
var flagChange = false;
var orignLength = 0;
var y = 0;
var checkAnyNewLivePostId;
var getStatisticId;
var lastMsgCreatedTime = 0;
var lastLivePostCreatedTime = 0;
var lastMsgId = 1;
var historyLivePostId = 0;
var lastChattingMsgId = 0;
var lastHistoryChattingMsgId = 0;
var pullUpEl;
var pullDownEl;
var mutualPullDownEl;
var yTmp = 0;
var isPulled = false;
var minPicPostfix = "!thumbnails";
var imgItems = [];
var screenWidth = 320;
var imgHeight = 480;
var isInLiveArea = true;
var unreadLiveMsgNum = 0;
var unreadInteractionMsgNum = 0;
var localBlackList = [];
var localAdminList = [];
var serverId="";
var isCreatable = true;
var adminID = "";
var isFirstload = true;


var loaded =function() {

    screenWidth = $(window).width();
    pullUpEl = $("#pullUp");
    pullDownEl = $("#pullDown");
    mutualPullDownEl = $("#mutualPullDown");
    myScroll = new IScroll('#livepanel', {
        mouseWheel: true,
        tap: true,
        click: true,
        // preventDefault: true,
        // preventDefaultException: {
        //     tagName: /^(INPUT|TEXTAREA|BUTTON|SELECT|DD|DIV|SPAN|P)$/,
        //     className: /(^|\s)msg-content(\s|$)/
        // },
        probeType: 2,
        scrollbars: true,
        fadeScrollbars: true,
        bounce: true,
        interactiveScrollbars: true,
        momentum:true// 允许有惯性滑动
    });


    parseLiveBubble();
   
    mutual = new IScroll('#mutual', {
        mouseWheel: true,
        click: true,
        // preventDefault: true,
        // preventDefaultException: {
        //     tagName: /^(INPUT|TEXTAREA|BUTTON|SELECT|DD|DIV|SPAN|P)$/
        // },
        probeType: 2,
        scrollbars: true,
        fadeScrollbars: true,
        bounce: true,
        interactiveScrollbars: true,
        momentum:true// 允许有惯性滑动
    });

    tabContent = new IScroll('#tabContent', {
        scrollX: true,
        scrollY: false,
        snap: ".tab-pane",
        snapSpeed: $(window).width(),
        eventPassthrough: true, //横轴滚动时，如想使用系统立轴滚动并在横轴上生效
        freeScroll: true, // 全方向允许滚动
        probeType: 2,
        bounce: true,
        interactiveScrollbars: true,
        momentum:true
    });
    //轮询，如有新直播报道则加载
    checkAnyNewLivePostId = setInterval(checkAnyNewLivePost, 5000);
    //从服务器请求互动区内的聊天记录
    checkAnyNewInteractionMsg();

    getStatistic();
    
    getStatisticId = setInterval(getStatistic, 15000);


    myScroll.on("scroll",function(){
        if(this.y > 70){
            pullDownEl.removeClass("loading").addClass("flip");
            pullDownEl.find(".pullDownLabel").text("松手开始加载...");
            isPulled = true;
        }

    });
    myScroll.on("scrollEnd",function(){
        if( isPulled){
            pullDownEl.find(".pullDownLabel").text("加载中...");
            pullDownEl.css("marginTop","0px").removeClass("flip").addClass("loading");
            getHistoryLivePost();
            isPulled = false;
        }
    });

    mutual.on("scroll",function(){
        if(this.y > 70){
            mutualPullDownEl.removeClass("loading").addClass("flip");
            mutualPullDownEl.find(".pullDownLabel").text("松手开始加载...");
            isPulled = true;
        }
    });
    mutual.on("scrollEnd",function(){
        if( isPulled ){
            mutualPullDownEl.find(".pullDownLabel").text("加载中...");
            mutualPullDownEl.css("marginTop","0px").removeClass("flip").addClass("loading");
            getHistoryInteractionMsg();
            isPulled = false;
        }
    });

    tabContent.on("scrollEnd",function(){
        // console.log(this.currentPage.pageX);
        if(this.currentPage.pageX == 0){

            isInLiveArea = true;
            unreadLiveMsgNum = 0;
            $("#livePanelLi small").text("");
            if($("#startBroadcast").length>0){
                $(".replay-area").hide();
                $("#startBroadcast").show();
            }
            $("#myTabs").children("li").first().addClass("active").siblings().removeClass("active");
            currentX = this.x;
        }else if(this.currentPage.pageX == 1){
            pauseAllVideo();
            isInLiveArea = false;
            mutual.refresh();
            $(".replay-area").hide();
            $("#reply").show();
            $("#myTabs").children("li").last().addClass("active").siblings().removeClass("active");
            currentX = this.x;
            unreadInteractionMsgNum = 0;
            $("#interactionPanelLi small").text("");
        }
    });

    Array.prototype.indexOf = function(e){
      for(var i=0,j; j=this[i]; i++){
        if(j==e){return i;}
      }
      return -1;
    }

    wechatJsapi.init();


    $("#wrapper").css("height",$(window).height()-$("#live-header").height()+"px");

    var i = 0;
    var pid;
    var index = 0;
    $(".replay-area").hide().eq(0).show();
    $('#myTabs a.tab-btn').each(function(){
        this.addEventListener("touchstart",function(){
            $(this).parent("li").addClass("active").siblings().removeClass("active");
            index = $(this).parent("li").index();
            pid = $(this).attr("pid");
            // tabContent.scrollToElement($(".tab-pane").eq(index).get(0));
            tabContent.goToPage(index,0,500);
            flagChange = true;
            if(pid == "#livepanel"){
                isInLiveArea = true;
                unreadLiveMsgNum = 0;
                $("#livePanelLi small").text("");
                myScroll.refresh();
                if($("#startBroadcast").length>0){
                    $(".replay-area").hide();
                    $("#startBroadcast").show();
                }
            }
            if(pid == "#mutual"){
                pauseAllVideo();
                isInLiveArea = false;
                mutual.refresh();
                $(".replay-area").hide();
                $("#reply").show();
                unreadInteractionMsgNum = 0;
                $("#interactionPanelLi small").text("");
            }

        },false);
    });

    // share
    if($("#shareBox").get(0)){
        $("#liveShare").get(0).addEventListener("touchend",function(){
            $("#shareBox").fadeIn(500);
            $(".share-box").addClass("open");
        },false);
        $("#shareClose").get(0).addEventListener("touchend",function(){
            $("#shareBox").fadeOut(500);
            $(".share-box").removeClass("open");
        },false);
        $(".share-box").get(0).addEventListener("touchend",function(e){
            e.stopPropagation();
            return false;
        },false);
        $("#shareBox").get(0).addEventListener("touchend",function(){
            $(this).fadeOut(500);
            $(".share-box").removeClass("open");
        },false);
    }
    // subscription
    if($("#subscriptionBox").get(0)){
        $("#subBtn").get(0).addEventListener("touchend",function(){
            $("#subscriptionBox").fadeIn(500);
            $(".share-box").addClass("open");
        },false);
        $("#subClose").get(0).addEventListener("touchend",function(){
            $("#subscriptionBox").fadeOut(500);
            $(".share-box").removeClass("open");
        },false);
        $(".share-box").get(0).addEventListener("touchend",function(e){
            e.stopPropagation();
            return false;
        },false);
        $("#subscriptionBox").get(0).addEventListener("touchend",function(){
            $(this).fadeOut(500);
            $(".share-box").removeClass("open");
        },false);
    }
    // panel
    if($("#panelBox").get(0)){
        $("#myBroadcast").get(0).addEventListener("touchend",function(e){
            e.stopPropagation();
            isSubscribe=($("#subcribe").length>0) && ($("#subcribe").val()=="true");
            console.log("isSubscribe="+isSubscribe);
            if(isSubscribe){
                return true;
            }else{
                $("#panelBox").fadeIn(500);
                $(".share-box").addClass("open");
                return false;
            }
        },false);
        $("#paneClose").get(0).addEventListener("touchend",function(){
            $("#panelBox").fadeOut(500);
            $(".share-box").removeClass("open");
        },false);
    }
  

    $("#fixedInput").on("focusin", function() {
        if (!$(this).parents("#replay").hasClass("fixReplay")) {
            $(this).parents("#reply").addClass("fixReplay");
        }
        $(".input-placeholder").show();
    });

    $("#reply > div").on("click", function(e) {
        e.stopPropagation();
        if($("#replay").hasClass("fixReplay")){
            $(".input-placeholder").hide();
        }
    });

    $("#reply").on("click", function(e) {
        $(this).removeClass("fixReplay");
        $(".input-placeholder").hide();
        clearReplyInfo();
    });
    $("#sendComment").on("click",function(e){
        e.stopPropagation();
       $(".input-placeholder").hide();
       clearReplyInfo();
    });


    // manage list
    $("#manageList .list-group-item").on("click", function() {
        $(this).find("strong i").toggleClass("checked");
        $(this).attr("data-value", $(this).attr("data-value") == "true" ? "flase" : "true");
    });

}
document.addEventListener('touchmove', function(e) {
    e.preventDefault();
}, false);


$(window).load(function() {
    //delay to set 'share' settings
    setTimeout('share()',3000);
});


function pauseAllVideo(){
    $("video").each(function(){
                    this.pause();
                });
}
function editImgList(){
           // edit img list
        var img_h = 0;
        $(".upload-img-item").each(function() {
            _this = $(this);
            if (img_h < $(this).width()) {
                img_h = $(this).width()
            }
        });
        $(".upload-img-item").css("height", img_h + "px");
};


function getRandomStr() {
    var text = "";
    var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    for (var i = 0; i < 16; i++) {
        text += possible.charAt(Math.floor(Math.random() * possible.length));
    }

    return text;
};

//wechat object
var wechatJsapi = {
    timestamp: null,
    nonceStr: null,
    signature: null,
    appId: null,
    url: null,
    self: null,

    //初始化(同时获取signature和paysign)
    init: function() {
        self = this;
        self.timestamp = Math.floor(Date.now() / 1000);
        self.nonceStr = getRandomStr();
        self.url = encodeURIComponent(location.href.split('#')[0]);
        $.get("/faxsun-info/api/v1/wechatJsapiSign", {
            timestamp: self.timestamp,
            nonceStr: self.nonceStr,
            url: self.url

        }, function(data) {
            self.appId = data.appId;
            self.signature = data.signature;

            //调用微信Config方法初始化配置
            wx.config({
                debug: false,
                appId: self.appId,
                timestamp: self.timestamp,
                nonceStr: self.nonceStr,
                signature: self.signature,
                jsApiList: ['chooseImage', 'uploadImage','onMenuShareTimeline','onMenuShareAppMessage']
            });

            //config信息验证后会执行ready方法
            wx.ready(function() {

                showChooseUploadImg();
                initChooseUploadImg();

                wx.error(function(res) {
                    console.log(res.toString());
                });

                wx.checkJsApi({
                    jsApiList: ['chooseImage', 'uploadImage','onMenuShareTimeline','onMenuShareAppMessage'],
                    success: function(res) {
                        console.log(res.toString());
                        // 以键值对的形式返回，可用的api值true，不可用为false
                        // 如：{"checkResult":{"chooseImage":true},"errMsg":"checkJsApi:ok"}
                    }
                });
            });
       


        });
    }

}

function share(){
         //分享到朋友圈
            wx.onMenuShareTimeline({
                title: "[直播中]"+$("#channelTopic_hidden").attr("topic"), // 分享标题
                link: 'http://www.faxsun.com/faxsun-info/live/broadcast/'+$("#channelId_hidden").attr("channelid"),
                imgUrl:$('#channelCover_hidden').attr("cover"),
                success: function () {
                    // 用户确认分享后执行的回调函数
                },
                cancel: function () {
                    // 用户取消分享后执行的回调函数
                }
            });
            //发送给朋友
            wx.onMenuShareAppMessage({
                title: "[直播中]"+$("#channelTopic_hidden").attr("topic"), // 分享标题
                link: 'http://www.faxsun.com/faxsun-info/live/broadcast/'+$("#channelId_hidden").attr("channelid"),
                desc:$('#channelDesc_hidden').attr("desc"),
                imgUrl:$('#channelCover_hidden').attr("cover"),
                type: '', // 分享类型,music、video或link，不填默认为link
                dataUrl: '', // 如果type是music或video，则要提供数据链接，默认为空
                success: function () {
                    // 用户确认分享后执行的回调函数
                },
                cancel: function () {
                    // 用户取消分享后执行的回调函数
                }
            });
}

function initChooseUploadImg() {
    $("#chooseUploadImg").on("click", function() {
        chooseAndUploadImgs();
    });

    $("#chooseUploadImgPlus").on("click", function() {
        chooseAndUploadImgs();
    });
}


function showChooseUploadImgPlus() {
    $("#chooseUploadImgPlus").css("display", "table");
}

function showChooseUploadImg() {
    $("#chooseUploadImg").css("display", "block");
}

function moveToLiveArea( author, content){
      $("#liveMsgJSON > #textarea").attr("value", author+": "+content) ;
        $.ajax({
            type: "POST",
            dataType: "html",
            url: "/faxsun-info/api/v1/live/post",
            data: $('#liveMsgJSON').serialize(),
            success: function(data) {
                $("#textArea").text("");
                //jump to braodcast page
                window.location.href="/faxsun-info/live/broadcast/"+$("#channelId_hidden").attr("channelid");
                return false;
            },
            error: function(data) {
                console.log("error:" + JSON.stringify(data));
            }
        });
}

//post the live msg  to the back end
function sendLiveMsg(o) {
    if(""==$("#textArea").val() && $("#img_tmp_container img").size()==0){
        alert("您未输入任何文字或图片");
    }
    else{
         var $live_form_submit = $("#live_form_submit");
        $.each($('#img_tmp_container  div.upload-img-item  img'), function(i) {
            var $input = $('<input name="content.url[' + i + ']" style="display:none" value="' + $(this).attr("serverId") + '"/>');
            $live_form_submit.before($input);
        });
        $("div.mark-bg").css("display","block");
        $.ajax({
            type: "POST",
            dataType: "html",
            url: "/faxsun-info/api/v1/live/post",
            data: $('#liveMsgJSON').serialize(),
            success: function(res) {
                var data = $.parseJSON(res);
                if(data.code==0){
                    var href = "/faxsun-info/live/broadcast/"+$("#channelId_hidden").attr("channelid");
                     window.location= href;
                     window.location.href= href;

                     setTimeout('postponedRedirect()',1000);
                     return false;
                }
                else if(data.code<0){
                    alert(data.message);
                    window.location.href="/faxsun-info/live/broadcast/"+$("#channelId_hidden").attr("channelid");
                    return false;
                }
               
            },
            error: function(data) {
                console.log("error:" + JSON.stringify(data));
            }
        });
        
    }
   
}

function postponedRedirect(){
    var href = "/faxsun-info/live/broadcast/"+$("#channelId_hidden").attr("channelid");
    $("#textArea").val("");
    window.location= href;
    window.location.href= href;
    return false;
}


var syncUpload = function(localIds) {
    var localId = localIds.pop();
    exhibitImg(localId);
    wx.uploadImage({
        localId: localId,
        isShowProgressTips: 1,
        success: function(res) {
            var serverId = res.serverId; // 返回图片的服务器端ID
            $('#img_tmp_container > div.col-xs-4 > img[src^="'+localId+'"]').attr("serverId",serverId);
            if (localIds.length > 0) {
                syncUpload(localIds);
            }
        }
    });
};

//delete the chosen pic
function removePic(o){
    $(o).parent().remove();
}

//将选中的图片展现出来
function exhibitImg(localId) {

    var $img = $('<div class="col-xs-4 upload-img-item"><button onclick="removePic(this)" class="upload-img-delete">x</button><img  src="' + localId + '"/></div>');
    $("#chooseUploadImgPlus").before($img);
}

//选择并上传图片到微信服务器
function chooseAndUploadImgs() {
    if ($('#img_tmp_container  div.upload-img-item  img').size() < 3) {
        wx.chooseImage({
            success: function(res) {
                var localIds = res.localIds; // 返回选定照片的本地ID列表，localId可以作为img标签的src属性显示图片
                if (localIds.length > 3) {
                    alert("一次最多只能上传3张图片");
                } else {
                    syncUpload(localIds);
                    showChooseUploadImgPlus();
                }
            }
        });
    } else {
        alert("一次最多只能上传3张图片");
    }

}

function initailRefreshScroll(){
    myScroll.refresh();
    if($('#scroll-1 .live-msg-bubble').size()>0){
        myScroll.scrollToElement($('#scroll-1 .live-msg-bubble').last().get(0),"none");
    }
    y = myScroll.y;
}



function refreshScrollHistory(){
    myScroll.refresh();
}

function refreshScroll(){
    if(myScroll.y > y){
        myScroll.refresh();
    }
    else{
        myScroll.refresh();
        myScroll.scrollToElement($('#scroll-1 .live-msg-bubble').last().get(0),"none");
        y = myScroll.y;
    }
}


function showFullScreen(o,area){
    organizeImgItems(area);
    var minSrc = $(o).attr("src");
    var unminSrc = minSrc.substring(0,minSrc.length - minPicPostfix.length);
    wx.previewImage({
        current: unminSrc, // 当前显示图片的http链接
        urls: imgItems// 需要预览的图片http链接列表
    });
}

function organizeImgItems(area){

      imgItems = [];
      var tab = "#livepanel";
      if("interaction"==area){
         tab = "#mutual";
      }
      $.each($(tab+" .live-msg-bubble dd .msg-content img"), function(i) {
            var $originalImg =  $(this);
           
            var minSrc = $originalImg.attr("src");
            var unminSrc = minSrc.substring(0,minSrc.length - minPicPostfix .length);
            imgItems.push(unminSrc);

      });
}

function getDate(createdTime){
        var newTimeDate = new Date(parseInt(createdTime)).format("MM-dd");
        var currentDate = new Date().format("MM-dd");
        var timePrefix = "";
        if(newTimeDate!=currentDate){
            timePrefix = newTimeDate + "  ";
        }
        return timePrefix;
}

//when GET the page from the back end, we need to parse the live post msg
function parseLiveBubble() {
    var hasImg = false;
    $.each($("#livepanel dl dd"), function(i) {

        var isVideo = false;
        var isFirst = true;
        var $dl = $(this).parent();
        var createdTime  = $dl.attr("date");
        if(createdTime -  lastLivePostCreatedTime > 180000 ){
          
            var timePrefix = getDate(createdTime);
            var newTime = new Date(parseInt(createdTime)).format("hh:mm");
            var $timeObj =  $('<div class="deline-time"><span>'+timePrefix+newTime+'</span></div>');
            $dl.before($timeObj);
        }
        lastLivePostCreatedTime = createdTime;
        var contentJson = $.parseJSON($(this).attr("content"));
        $(this).removeAttr("content");

        var strDom = '<div class="msg-content"><p>' + contentJson.text + '</p>';
        var str = '';
        
        for (var i = 0; i < contentJson.url.length; i++) {
           if(isFirst){
                isFirst = false;
                var firstUrl = contentJson.url[0];
                var re = /mp4$/; 
                if(re.test(firstUrl)){
                    isVideo = true;
                }
           }

           if(isVideo){
                strDom += '<video controls="" ><source src="'+contentJson.url[i]+'" type="video/mp4" /> Your browser does not support HTML5 video.</video>'
           }
           else{
                hasImg = true;
                if(contentJson.url[i].indexOf("http")==0){
           
                
                //if(i==(contentJson.url.length-1)){
                     str = 'onload="initailRefreshScroll()"';
                //}
                     strDom +=  '<img '+str+'src="' + contentJson.url[i] + minPicPostfix + '" onclick="showFullScreen(this,\'live\')" />';
                }
           }
           
        }
        strDom += '</div>';
        $(this).append(strDom);

    });
    initThumbupAndComment();
    if(!hasImg){
        initailRefreshScroll();
    }
}


function organizeLiveTag(msg,i,msgslength){ 
    var str = '<dl class="live-msg-bubble msg-left" userid="'+msg.user.id+'">' +
            '<dt><a href="#"><img src="' + msg.user.avatar + '"  /></a></dt>' +
            '<dd msgid="' + msg.id + '" >';
    var content = msg.content;

    str +=  '<div class="msg-author"><span>'+msg.user.name+
    '</span><div class="msg-like"><a href="#" msgId="'+msg.id+'" class="msg-favour"><i class="glyphicon glyphicon-thumbs-up"></i><b>'+msg.thumbsup+'</b></a><a href="#" msgId="'+msg.id+'" class="msg-discuss">'+
    '<i class="glyphicon glyphicon-comment"></i><b>'+msg.comments+'</b></a></div></div><div class="msg-content">';
    str += '<p>' + content.text + '</p>';
    var strOnload = '';

    var isFirst = true;
    var isVideo = false;
    for (var j = 0; j < content.url.length; j++) {
           if(isFirst){
                isFirst = false;
                var firstUrl = content.url[0];
                var re = /mp4$/; 
                if(re.test(firstUrl)){
                    isVideo = true;
                }
           }
           if(isVideo){
                str +=  '<video controls="" ><source src="'+content.url[j]+'" type="video/mp4" /> Your browser does not support HTML5 video.</video>'
           }
           else{
                if(i==msgslength-1){
                     strOnload = 'onload="refreshScroll()"';
                }
                str = str + '<img '+strOnload+' src="' + content.url[j] + minPicPostfix + '" onclick="showFullScreen(this,\'live\')"/>'
           } 
    }
    str = str + '</dd></dl>';
    return str;
}


//display the live post
function loadNewMsgs(msgs) {
    var $livepanel = $('#livepanel .scroll-panel');
    for (var i = 0; i < msgs.length; i++) {
        
        var createdTime  = msgs[i].date;
        if(createdTime -  lastLivePostCreatedTime > 180000 ){
            var timePrefix = getDate(createdTime);
            var newTime = new Date(parseInt(createdTime)).format("hh:mm");
            var $timeObj =  $('<div class="deline-time"><span>'+timePrefix+newTime+'</span></div>');
            $livepanel.append($timeObj);
        }
        lastLivePostCreatedTime = createdTime;
        

        var str = organizeLiveTag(msgs[i],i,msgs.length);
        var $msg = $(str);
        $livepanel.append($msg);

    }
    initThumbupAndComment();
    refreshScroll();

}

function loadHistoryMsgs(msgs){
    var $pullDown = $('#pullDown');
    for (var i = ( msgs.length -1 ); i >= 0 ; i--) {
        var str = organizeLiveTag(msgs[i],i,msgs.length);
        var $msg = $(str);
        $pullDown.after($msg);
        if(i>=1){
            var createdTime = msgs[i].date;
            var createdTimePre = msgs[i-1].date;
            if(createdTime -  createdTimePre > 180000 ){
                var timePrefix = getDate(createdTime);
                var newTime = new Date(parseInt(createdTime)).format("hh:mm");
                var $timeObj =  $('<div class="deline-time"><span>'+timePrefix+newTime+'</span></div>');
                $pullDown.after($timeObj);
            }
        }
        else{
            var createdTime  = msgs[i].date;
            var timePrefix = getDate(createdTime);
            var newTime = new Date(parseInt(createdTime)).format("hh:mm");
            var $timeObj =  $('<div class="deline-time"><span>'+timePrefix+newTime+'</span></div>');
            $pullDown.after($timeObj);
        }
       
    }
    initThumbupAndComment();
    refreshScrollHistory();

}
var st;
function refreshLiveArea(ele){
    var responseJokeMsg = [
        "服务器被你刷崩溃，再刷？小编上门查水表了！",
        "你好，我是直播君的自动回复，现在他不在，跟我说什么我也就这几句……",
        "直播君去用膳了，众卿家跪安吧！",
        "hi~老板不在，直播君去打魔兽了！",
        "你真的要再刷？你确定自己想刷？你一定非刷不可吗？那你刷吧，这是自动回复。",
        "直播君在卿不在，卿在直播君无踪。问世间缘是何物？直教你我难相逢！",
        "直播君最近迷上了广场舞，认真学习中，勿扰！",
        "现场美女太多了，直播君被迷晕啦！",
        "直播君偷看美女被揍了，现在医院休养中……",
        "直播君去买下午茶了，不要告诉老板，回来给你带份红烧肉！",
        "直播君在写国际关系论文，请勿打扰国家社稷民生大计的制定！",
        "直播君长的太帅被保安大叔拦在门外了！",
        "直播君最近胖了，郁闷中，勿扰！"
    ];
    $(ele).addClass("loading");
    if($("#livepanel dl dd").size()>0){
        var lastMsgId = $("#livepanel dl dd").last().attr("msgid");
    }

    getStatistic();

    $.ajax({
        type: "GET",
        data: {
            "msgid": lastMsgId,
            "channelid": $("#channelId_hidden").attr("channelid")
        },
        url: "/faxsun-info/api/v1/live/newMsg",
        success: function(data) {
            if(data.data.msgs && data.data.msgs.length>0){
                loadNewMsgs(data.data.msgs);
            }
            else{
                var i = Math.round(Math.random()*responseJokeMsg.length);
                $("#callBroadcaster").text(responseJokeMsg[i]);
                if(st){clearTimeout(st);}
                $("#manual_refresh").stop(true).fadeIn();
                st = setTimeout(function(){
                    $("#manual_refresh").fadeOut();
                },6000);
                $(ele).removeClass("loading");
            }
        },
        error: function(xhr, error) {
             console.log(error + "-更新出错，请稍后再试直播区");
        }
    });
}

//get the newest live post and display it in the live area
var checkAnyNewLivePost = function() {
    if($("#livepanel dl dd").size()>0){
        var lastMsgId = $("#livepanel dl dd").last().attr("msgid");
    }
    $.ajax({
        type: "GET",
        data: {
            "msgid": lastMsgId,
            "channelid": $("#channelId_hidden").attr("channelid")
        },
        url: "/faxsun-info/api/v1/live/newMsg",
        success: function(data) {
            if(data.data.msgs && data.data.msgs.length>0){
                loadNewMsgs(data.data.msgs);
                if(!isInLiveArea){
                    unreadLiveMsgNum += data.data.msgs.length;
                    $("#livePanelLi small").text("("+unreadLiveMsgNum+")");
                }
            }
            
            
        },
        error: function(xhr, error) {
             console.log(error + "-更新出错，请稍后再试直播区");
        }
    });
}


//get the newest live post and display it in the live area
var getHistoryLivePost = function() {
    if($("#livepanel dl dd").size()>0){
        var historyLivePostId = $("#livepanel dl dd").first().attr("msgid");
    }
    
    $.ajax({
        type: "GET",
        data: {
            "msgid": historyLivePostId,
            "channelid": $("#channelId_hidden").attr("channelid")
        },
        url: "/faxsun-info/api/v1/live/history",
        success: function(data) {
            loadHistoryMsgs(data.data.msgs);
            pullDownEl.find(".pullDownLabel").text("下拉加载历史消息...");
            pullDownEl.removeClass("flip").removeClass("loading").css("marginTop","-40px");
        },
        error: function(xhr, error) {
             console.log(error + "-更新出错，请稍后再试直播区");
        }
    });
}

//send chatting msg which will be displayed in the interaction area
function sendComment(self){
    if(""!=$("#fixedInput").val()){
        if(localBlackList.indexOf($("#userId_hidden").attr("userId")) < 0 ){  //not in the black list
             var val = $("#fixedInput").val();
            $("#fixedInput").val("");
            //disable the sendComment function temporarily
             $(self).removeAttr("ontouchstart");
             //将自己发送的消息临时显示在聊天区
             var $msgObj =  $('<dl class="live-msg-bubble msg-right host selfTmpMsg" userid="-1" msgid="-1">'+
                            '<dt><a href="#"><img src="'+$(self).attr("useravatar")+'"/></a></dt><dd><div class="msg-author"><span>'+
                            $("#userName_hidden").attr("userName")+'</span></div><div class="msg-content"><p>'
                            + val+'</p></div></dd></dl>');


            $("#mutual #scroll-2").append($msgObj);

            $.ajax({
                type : "POST",
                url : '/faxsun-info/comment/post', 
                data : {
                   "text" : val,
                   "type" : 3,
                   "toId" : $("#channelId_hidden").attr("channelid")
                  },
                  success : function(data) {
                    var ret = JSON.parse(data);
                  if (ret.code < 0) {
                    alert(ret.message);
                    if (ret.code == -2) {
                      // 未登录
                     // $('#trigger-overlay').trigger('click');
                       alert("您尚未登录！");
                    }
                  } else if (ret.code == 0) {
                        $("#fnNave").find("li").eq(1).addClass("active").siblings().removeClass("active");
                        $("#mutual").addClass("active").siblings().removeClass("active");

                        $("#fixedInput").val("");
                        $("#reply").removeClass("fixReplay");

                        mutual.refresh();
                        mutual.scrollToElement($("#scroll-2").find(".live-msg-bubble").last().get(0),"none");
                        tabContent.goToPage(1,0,500);

                  } else {
                    removeSelfTmpMsg();
                    alert(ret.message);
                  }
                }
            });
            $(self).attr("ontouchstart","sendComment(this)");
        }
        else{
            alert("您已被直播员禁言！");
        }
    }
    
   
}

// 对Date的扩展，将 Date 转化为指定格式的String 
// 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符， 
// 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字) 
// 例子： 
// (new Date()).Format("yyyy-MM-dd HH:mm:ss.S") ==> 2006-07-02 08:09:04.423 
// (new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18 
Date.prototype.format = function(fmt) 
{ //author: meizz 
  var o = { 
    "M+" : this.getMonth()+1,                 //月份 
    "d+" : this.getDate(),                    //日 
    "h+" : this.getHours(),                   //小时 
    "m+" : this.getMinutes(),                 //分 
    "s+" : this.getSeconds(),                 //秒 
    "q+" : Math.floor((this.getMonth()+3)/3), //季度 
    "S"  : this.getMilliseconds()             //毫秒 
  }; 
  if(/(y+)/.test(fmt)) 
    fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length)); 
  for(var k in o) 
    if(new RegExp("("+ k +")").test(fmt)) 
    fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length))); 
  return fmt; 
}

///////////////
//////////////////////////////////////////////////////////////
//get newest chatting records in interaction area
var checkAnyNewInteractionMsg = function() {
    
    $.ajax({
        type: "GET",
        data: {
             "liveId" : $("#channelId_hidden").attr("channelid"),
             "startId" : lastChattingMsgId,
             "size" : 30
        },
        url: "/faxsun-info/api/v1/liveComment",
        contentType : "application/json; charset=utf-8",
        success: function(data) {
            var comments_blacklist = data.comments_blacklist;
             if(comments_blacklist){

                   var localAdminList = comments_blacklist.managerlist;
                   adminID = comments_blacklist.adminID;
                   if(comments_blacklist.comments && comments_blacklist.comments.length > 0){  
                     if(isInLiveArea){
                        if(isFirstload){
                            isFirstload = false;
                        }
                        else{
                            unreadInteractionMsgNum += comments_blacklist.comments.length;
                            $("#interactionPanelLi small").text("("+unreadInteractionMsgNum+")");
                        }
                         
                    }             
                     // update startId on success return
                     var $mutual = $("#mutual #scroll-2");
                     var userId = $("#userId_hidden").attr("userId");
                     //delete the msg which is temporarily displayed
                     removeSelfTmpMsg();

                     //将返回来的评论显示在评论区
                     var isFirst = true;
                     for(var i=(comments_blacklist.comments.length - 1) ;i >= 0 ; i--){
                            var msgJsonObj = comments_blacklist.comments[i];
                            //display the time on the top of the msg list
                            if(isFirst){
                                if($("#mutual #scroll-2 dl").size()>0){
                                    lastMsgCreatedTime = $("#mutual #scroll-2 dl").last().attr("created");
                                }
                                //when it is the first time to request
                                if(lastChattingMsgId == 0){
                                    lastHistoryChattingMsgId = msgJsonObj.id ; 
                                }
                                isFirst = false;
                            }
                            //if the new msg is receive 3 min later, display a time tag 
                            if(msgJsonObj.created - lastMsgCreatedTime > 180000){
                                var timePrefix = getDate(msgJsonObj.created);
                                var newTime = new Date(msgJsonObj.created).format("hh:mm");
                                var $timeObj =  $('<div class="deline-time"><span>'+timePrefix+newTime+'</span></div>');
                                $mutual.append($timeObj);
                            }
                            if(i==0){
                                lastChattingMsgId = msgJsonObj.id;
                            }
                            var position = "left";
                          
                            var fankeAdmin = "";
                            //如果该消息的作者是直播员，
                            if(localAdminList.indexOf(msgJsonObj.author.id)>=0){
                                position = "left  manager";
                                fankeAdmin = "<small>直播员</small>";
                            }

                            //如果该消息的作者是管理员，
                            if(adminID == msgJsonObj.author.id){
                                position = "left  admin";
                                fankeAdmin = "<small>管理员</small>";
                            }

                              //如果是本用户发送的消息，则在右侧显示
                            if(userId == msgJsonObj.author.id){
                                position = "right  host";
                                fankeAdmin = "";
                            }

                            var originStr = organizeOriginStr(msgJsonObj,comments_blacklist);

                            var $msgObj =  $('<dl class="live-msg-bubble msg-'+position+'" created="'+msgJsonObj.created+'" userid="'+msgJsonObj.author.id+'" msgid="'+msgJsonObj.id+'">'+
                                '<dt><a href="#"><img src="'+msgJsonObj.author.avatar+'"/></a></dt><dd><div class="msg-author"><span>'+ msgJsonObj.author.name + fankeAdmin +
                                '</span></div><div class="msg-content">'+originStr+'<p>'+msgJsonObj.content+'</p></div></dd></dl>');
                            $mutual.append($msgObj);
                            lastMsgCreatedTime = msgJsonObj.created;  
                     }
                     

                     mutual.refresh();
                     mutual.scrollToElement($("#scroll-2").find(".live-msg-bubble").last().get(0));
                    // if("null" != $("#role_hidden").attr("role")){
                            bindLongPressListener($("#role_hidden").attr("role"),localAdminList); 
                    // }
                   }
                   // for each comment whose author id in blacklist, remove it from display
                   removeBlacklistMsgs(comments_blacklist);
                   setLocalBlackList(comments_blacklist)
                   mutual.refresh();
                   checkAnyNewInteractionMsg();
                   initOriginalMsgCollapse();
            }
        },
        error: function(xhr, error) {
            console.log(error + "-更新出错，请稍后再试互动区");
        }
    });
}


function organizeOriginStr(msgJsonObj,comments_blacklist){
        var str = "";
        if(4 == msgJsonObj.type){
            var toId = msgJsonObj.toId;
            var originObj = comments_blacklist.livemsgs[toId];
            if(originObj){
                str += '<div class="msg-origin">';
                if(originObj.content.text){
                     str += '<p>'+originObj.content.text+'</p>';
                }
                if(originObj.content.url && originObj.content.url.length>0){
                    var isFirst = true;
                    var contentJson =  originObj.content;
                    var isVideo = false;
                    var onloadStr = "";
                    for (var i = 0; i < contentJson.url.length; i++) {
                           if(isFirst){
                                isFirst = false;
                                var firstUrl = contentJson.url[0];
                                var re = /mp4$/; 
                                if(re.test(firstUrl)){
                                    isVideo = true;
                                }
                           }

                           if(isVideo){
                                str += '<video controls="" ><source src="'+contentJson.url[i]+'" type="video/mp4" /> Your browser does not support HTML5 video.</video>'
                           }
                           else{
                                str +=  '<img src="' + contentJson.url[i] + minPicPostfix + '" onclick="showFullScreen(this,\'interaction\')" />';
                           }
                           
                    }
                }
                str += ' <div class="unfold"><span class="glyphicon glyphicon-chevron-down"></span></div>';
                str += '</div>';
            }
        }
        return str;

}

//get newest chatting records in interaction area
var getHistoryInteractionMsg = function() {
    
    $.ajax({
        type: "GET",
        data: {
             "liveId" : $("#channelId_hidden").attr("channelid"),
             "endId" : lastHistoryChattingMsgId,
             "size" : 30
        },
        url: "/faxsun-info/api/v1/liveComment",
        contentType : "application/json; charset=utf-8",
        dataType : "json",
        success: function(data) {
            var comments_blacklist = data.comments_blacklist;
             if(comments_blacklist){
                   var localAdminList = comments_blacklist.managerlist;
                   adminID = comments_blacklist.adminID;
                   if(comments_blacklist.comments && comments_blacklist.comments.length > 0){               
                     // update startId on success return
                     var $mutualPullDown = $("#mutualPullDown");
                     var userId = $("#userId_hidden").attr("userId");
                     //将返回来的评论显示在评论区
                     for(var i=0 ;i < comments_blacklist.comments.length ; i++){
                            var msgJsonObj = comments_blacklist.comments[i];
                            var msgJsonObjPre = null;
                           
                            var position = "left";
                            var fankeAdmin = "";

                             //如果该消息的作者是直播员，
                            if(localAdminList.indexOf(msgJsonObj.author.id)>=0){
                                position = "left  manager";
                                fankeAdmin = "<small>直播员</small>";
                            }

                            //如果该消息的作者是管理员，
                            if(adminID == msgJsonObj.author.id){
                                position = "left  admin";
                                fankeAdmin = "<small>管理员</small>";
                            }

                            //如果是本用户发送的消息，则在右侧显示
                            if(userId == msgJsonObj.author.id){
                                position = "right  host";
                                fankeAdmin = "";
                            }

                            var originStr = organizeOriginStr(msgJsonObj,comments_blacklist);

                            var $msgObj =  $('<dl class="live-msg-bubble msg-'+position+'" created="'+msgJsonObj.created+'" userid="'+msgJsonObj.author.id+'" msgid="'+msgJsonObj.id+'">'+
                                '<dt><a href="#"><img src="'+msgJsonObj.author.avatar+'"/></a></dt><dd><div class="msg-author"><span>' + msgJsonObj.author.name + fankeAdmin +
                                '</span></div><div class="msg-content">'+originStr+'<p>'+msgJsonObj.content+'</p></div></dd></dl>');


                            $mutualPullDown.after($msgObj);

                             //display the time tag
                            if(i== (comments_blacklist.comments.length -1)){
                                var timePrefix = getDate(msgJsonObj.created);
                                var newTime = new Date(msgJsonObj.created).format("hh:mm");
                                var $timeObj =  $('<div class="deline-time"><span>'+timePrefix+newTime+'</span></div>');
                                $mutualPullDown.after($timeObj);
                                lastHistoryChattingMsgId = msgJsonObj.id;
                            }
                            else{
                                msgJsonObjPre = comments_blacklist.comments[i+1];
                                 //if the new msg is receive 3 min later, display a time tag 
                                if(msgJsonObj.created -msgJsonObjPre.created > 180000){
                                    var timePrefix = getDate(msgJsonObj.created);
                                    var newTime = new Date(msgJsonObj.created).format("hh:mm");
                                    var $timeObj =  $('<div class="deline-time"><span>'+timePrefix+newTime+'</span></div>');
                                    $mutualPullDown.after($timeObj);
                                }

                            }
                     }
                     mutual.refresh();
                     bindLongPressListener($("#role_hidden").attr("role"),localAdminList); 
                    
                   }
                   mutualPullDownEl.find(".pullDownLabel").text("下拉加载历史消息...");
                   mutualPullDownEl.removeClass("flip").removeClass("loading").css("marginTop","-40px");
                   // for each comment whose author id in blacklist, remove it from display
                   removeBlacklistMsgs(comments_blacklist);
                   setLocalBlackList(comments_blacklist)
                   mutual.refresh();
                   initOriginalMsgCollapse();

            }
        },
        error: function(xhr, error) {
            console.log(error + "-更新出错，请稍后再试互动区");
        }
    });
}

function removeBlacklistMsgs(comments_blacklist){
     if(comments_blacklist.blacklist && comments_blacklist.blacklist.length > 0){
          $.each($("#mutual  dl"), function(i) {
                if(comments_blacklist.blacklist.indexOf(parseInt($(this).attr("userid")))>-1){
                    //某条评论的作者被禁言，则删去该评论
                    if("deline-time"==$(this).prev().attr("class")){
                        //如果被删去的评论前面有时间tag，则把时间标记也删掉
                        $(this).prev().remove();
                    }
                    $(this).remove();
                }
           });
   }
}

function setLocalBlackList(comments_blacklist){
     if(comments_blacklist.blacklist){
         localBlackList = comments_blacklist.blacklist;
   }
}

//delete the msg which is temporarily displayed
function removeSelfTmpMsg(){
    $("#mutual  dl.selfTmpMsg").remove();
}

function disableTalk(liveId, userId){
     $.ajax({
        type: "GET",
        url: "/faxsun-info/api/v1/live/talk/disable/"+userId+"/"+liveId,
        success: function(data) {
           
            hidePopupMenu();
            alert($.parseJSON(data).message);
        },
        error: function(xhr, error) {
            console.log(error + "-更新出错，请稍后再试 禁言");
        }
    });
}

function createChannel(){
    if(""!=$(".channel-tit input").val()){
         if (isCreatable) {
            $(".mark-bg").css("display","block");
            $("#createChannelBtn").removeAttr("onclick");
            $(".file-input").append('<input name="coverImage" style="display:none" value="' + serverId + '"/>');
            $.ajax({
                type: "POST",
                data: $('#createChannelForm').serialize(),
                url: "/faxsun-info/api/v1/live/channel/create",
                contentType : "application/x-www-form-urlencoded",
                dataType : "html",
                success: function(res) {
                    var data = $.parseJSON(res);
                    alert(data.message);
                    if(data.code==0){
                        window.location.href = data.data.url;
                        return false;
                    }
                    else if(data.code<0){
                        alert(data.message);
                         $(".mark-bg").css("display","none");
                         $("#createChannelBtn").attr("onclick","createChannel();return false;");
                    }
                },
                error: function(xhr, error) {
                    console.log(error + "-更新出错，请稍后再试互动区");
                }
            });

        }else{
            alert("请在图片上传完成后再点击我");
        }
    }
    else{
        alert("请输入直播名！");
    }
}



function uploadLiveCover(o){

     wx.chooseImage({
            success: function(res) {
                var localIds = res.localIds; // 返回选定照片的本地ID列表，localId可以作为img标签的src属性显示图片
                if (localIds.length > 1) {
                    alert("一次最多只能上传1张图片");
                } else {
                    $(o).empty();
                    $(o).append('<img src="'+localIds[0]+'" alt="channel-logo" class="img-rounded"/>');
                    isCreatable = false;
                    serverId = "";
                    wx.uploadImage({
                        localId: localIds[0],
                        isShowProgressTips: 1,
                        success: function(res) {
                            serverId = res.serverId; // 返回图片的服务器端ID
                            isCreatable = true;
                        }
                    });
                }
            }
        });

}


function getStatistic(){
     $.ajax({
        type: "GET",
        url: "/faxsun-info/api/v1/live/active/stats/"+$("#channelId_hidden").attr("channelid")+"?q="+Math.random(),
        success: function(data) {
           
            var jsonObj = $.parseJSON(data);
            if("success"==jsonObj.code){
                var nop = jsonObj.data.nop;
                if($(".live-person-number small font")){
                    $(".live-person-number small font").html(nop);
                }
            }
            else{
                alert(jsonObj.message);
            }

        },
        error: function(xhr, error) {
            console.log(error + "-更新出错，请稍后再试 禁言");
        }
    });
}

var commentToUserName = "";
var commentId = "";
function goToReplyState(userName,commentid){
     hidePopupMenu();
     $("#fixedInput").focus();
     commentToUserName = userName;
     commentId = commentid;
     $("#fixedInput").attr("placeholder","回复"+userName+":");
     $("#sendComment").attr("ontouchstart","replyComment(this)")
}

function clearReplyInfo(){
    commentToUserName = "";
    commentId = "";
    $("#fixedInput").attr("placeholder","说点什么吧");
     $("#fixedInput").val("");
    $("#sendComment").attr("ontouchstart","sendComment(this)");
     if("null"!=$("#role_hidden").attr("role")&&isInLiveArea){
        $("#reply").css("display","none");
    }
    
}


function replyComment(self){
     if(""!=$("#fixedInput").val()){
        if(localBlackList.indexOf($("#userId_hidden").attr("userId")) < 0 ){  //not in the black list
            var val = $("#fixedInput").val();
            $("#fixedInput").val("");
            //disable the sendComment function temporarily
             $(self).removeAttr("ontouchstart");
             //将自己发送的消息临时显示在聊天区
             var $msgObj =  $('<dl class="live-msg-bubble msg-right host selfTmpMsg" userid="-1" msgid="-1">'+
                            '<dt><a href="#"><img src="'+$(self).attr("useravatar")+'"/></a></dt><dd><div class="msg-author"><span>'+
                            $("#userName_hidden").attr("userName")+'</span></div><div class="msg-content"><p>'
                            + '回复'+commentToUserName+':' +val+'</p></div></dd></dl>');


            $("#mutual #scroll-2").append($msgObj);

            $.ajax({
                type : "POST",
                url : '/faxsun-info/comment/post/reply', 
                data : {
                   "text" : val,
                   "type" : 3,
                   "toId" : $("#channelId_hidden").attr("channelid"),
                   "commentId" :commentId,
                   "commentToUserName" : commentToUserName
                  },
                  success : function(data) {
                    var ret = JSON.parse(data);
                  if (ret.code < 0) {
                    alert(ret.message);
                    if (ret.code == -2) {
                      // 未登录
                     // $('#trigger-overlay').trigger('click');
                       alert("您尚未登录！");
                    }
                  } else if (ret.code == 0) {
                        $("#fixedInput").val("");
                        $("#reply").removeClass("fixReplay");

                        mutual.refresh();
                        mutual.scrollToElement($("#scroll-2").find(".live-msg-bubble").last().get(0),"none");
                        tabContent.goToPage(1,0,500);

                  } else {
                    removeSelfTmpMsg();
                    alert(ret.message);
                  }
                }
            });
            clearReplyInfo();
        }
        else{
            alert("您已被直播员禁言！");
        }
    }
}

function goToReplyLiveState(userName,commentid){
    if("null"!=$("#role_hidden").attr("role")){
        $("#reply").css("display","block");
    }
     $("#fixedInput").focus();
     commentToUserName = userName;
     commentId = commentid;
     $("#fixedInput").attr("placeholder","回复"+userName+":");
     $("#sendComment").attr("ontouchstart","replyLiveMsg(this,"+commentid+")")
}

function initOriginalMsgCollapse(){
     $(".unfold").each(function(){
        if(undefined==$(this).attr("isBinded")){
             this.addEventListener("touchstart",function(){
                $(this).parents(".msg-origin").toggleClass("autoHeight");
                mutual.refresh();
                setTimeout("mutualRefresh()",500);
            },false);
            $(this).attr("isBinded","yes")

           
        }
       
    });
}

function mutualRefresh(){
    mutual.refresh();
}

/////////////////////////////////////////////////////////////
function replyLiveMsg(self,commentid){
     if(""!=$("#fixedInput").val()){
        if(localBlackList.indexOf($("#userId_hidden").attr("userId")) < 0 ){  //not in the black list
            var val = $("#fixedInput").val();
            $("#fixedInput").val("");
            //disable the sendComment function temporarily
             $(self).removeAttr("ontouchstart");
             //将自己发送的消息临时显示在聊天区
             var $msgObj =  $('<dl class="live-msg-bubble msg-right host selfTmpMsg" userid="-1" msgid="-1">'+
                            '<dt><a href="#"><img src="'+$(self).attr("useravatar")+'"/></a></dt><dd><div class="msg-author"><span>'+
                            $("#userName_hidden").attr("userName")+'</span></div><div class="msg-content"><div class="msg-origin">'+
                            $("#livepanel dd[msgid="+commentid+"] .msg-content").html()+'<div class="unfold"><span class="glyphicon glyphicon-chevron-down"></span></div></div><p>'
                            + '回复'+commentToUserName+':' +val+'</p></div></dd></dl>');
            $("#mutual #scroll-2").append($msgObj);
            initOriginalMsgCollapse();
            $.ajax({
                type : "POST",
                url : '/faxsun-info/comment/post', 
                data : {
                   "text" : val,
                   "type" : 4,
                   "toId" : commentId
                  },

                  success : function(data) {
                    var ret = JSON.parse(data);
                  if (ret.code < 0) {
                    alert(ret.message);
                    if (ret.code == -2) {
                      // 未登录
                     // $('#trigger-overlay').trigger('click');
                       alert("您尚未登录！");
                    }
                  } else if (ret.code == 0) {
                        $("#fixedInput").val("");
                        $("#reply").removeClass("fixReplay");

                        mutual.refresh();
                        mutual.scrollToElement($("#scroll-2").find(".live-msg-bubble").last().get(0),"none");
                        tabContent.goToPage(1,0,500);
                        var $commentB = $("#livepanel dd[msgid="+commentid+"] a.msg-discuss b");
                        var originCommentNum = parseInt($commentB.text());
                        $commentB.text(originCommentNum+1);


                  } else {
                    removeSelfTmpMsg();
                    alert(ret.message);
                  }
                }
            });
            clearReplyInfo();

        }
        else{
            alert("您已被直播员禁言！");
        }
    }
}

function hidePopupMenu(){
    $(".dropdown-menu").remove();
     popupMenuFlag = false;
}

function grantManagerPermission(userid){

    hidePopupMenu();

     $.ajax({
            type: "POST",
            data:{
                "userid" : userid,
                "channelid" : $("#channelId_hidden").attr("channelid")
            },
            url: "/faxsun-info/api/v1/live/admin/addmanager",
            contentType : "application/x-www-form-urlencoded",
            dataType : "html",
            success: function(res) {
                var data = $.parseJSON(res);

                
                if(data.code==0){
                    alert(data.message+"  请告诉ta刷新页面生效");
                      window.location.reload();
                }
                else if(data.code<0){
                    alert(data.message);
                }
                
            },
            error: function(xhr, error) {
                console.log(error + "-更新出错，请稍后再试互动区");
            }
        });
}

function revokeManagerPermission(userid){

    hidePopupMenu();

     $.ajax({
            type: "POST",
            data:{
                "userid" : userid,
                "channelid" : $("#channelId_hidden").attr("channelid")
            },
            url: "/faxsun-info/api/v1/live/admin/removemanager",
            contentType : "application/x-www-form-urlencoded",
            dataType : "html",
            success: function(res) {
                var data = $.parseJSON(res);

                
                if(data.code==0){
                    alert(data.message);
                      window.location.reload();
                }
                else if(data.code<0){
                    alert(data.message);
                }
                
            },
            error: function(xhr, error) {
                console.log(error + "-更新出错，请稍后再试互动区");
            }
        });
}
